package org.academic.texteditor.gui.plugin.document;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;

import org.academic.texteditor.gui.PrincipalWindow;
import org.academic.texteditor.gui.component.PageContainer;
import org.academic.texteditor.gui.component.menu.MenuFactory;
import org.academic.texteditor.gui.component.toolbar.ToolBarFactory;
import org.academic.texteditor.gui.form.PageContainerForm;
import org.academic.texteditor.gui.plugin.BasePlugin;

public class SaveDocumentPlugin extends BasePlugin {

	private static final long serialVersionUID = 7599132008526800360L;
	
	public SaveDocumentPlugin() {
		super("saveDocumentPlugin");
	}

	@Override
	public void initialize(PageContainer pageContainer) {
		JMenu menu = MenuFactory.getApplication();
		MenuFactory.createMenuItem(menu, 2, "save", "menu.application.save", this).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
		menu.setVisible(true);
		
		JToolBar main = ToolBarFactory.getMain();
		ToolBarFactory.createButton(main, "save", 2, "toolbar.main.save", "images/save-icon.png", this);
	}
	
	@Override
	public void activate() {
		
	}

	@Override
	public void execute() {
		PageContainerForm document = PrincipalWindow.getInstance().getActualDocument();
		if (document == null) {
			return;
		}
		
		JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
		int returnVal = fileChooser.showSaveDialog(PrincipalWindow.getInstance());
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			
			try {
				FileWriter writer = new FileWriter(file);
				
				PageContainer pageContainer = document.getPageContainer();
				pageContainer.saveDocument(writer);
				
				writer.flush();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void deactivate() {

	}

	@Override
	public void destroy() {
		JMenu menu = MenuFactory.getApplication();
		MenuFactory.removeMenuItem(menu, "save");
		
		JToolBar main = ToolBarFactory.getMain();
		ToolBarFactory.removeButton(main, "save");
	}

}
